﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using WHMS.EntityClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;

namespace WMS
{
	public partial class AddItemsForSaleForm : Form
	{
		SupplyOrderEntity _currentSupplyOrder;
		TransactionEntity _currentTransaction;
		DepositTransactionEntity _currentDepositTransaction;
		DataMngrFormBase<SupplyOrderItemEntity> _tranItemsForm;
		List<ErrorProvider> _errorProviders;

		public AddItemsForSaleForm()
		{
			InitializeComponent();

            HideOrViewWeightCol();
		}

        private void HideOrViewWeightCol()
        {
            var weightCol = _transItemsGrid.Columns["WeightQtyAdded"];

            if (weightCol != null)
            {
                if (UserInfo.Roles.Where(r => r.ViewWorkshop == true).Count() > 0)
                {
                    weightCol.Visible = true;
                }
                else
                {
                    weightCol.Visible = false;
                }
            }
        }

		private void AddItemsForm_Load(object sender, EventArgs e)
		{			
			LoadData();

			_errorProviders = new List<ErrorProvider>();

			InitializeDataSources();
		}
		private void NewBtn_Click(object sender, EventArgs e)
		{
			//InitializeDataSources();
			//ResetTransactionItems();
			ResetForm();
		}
		private void SaveBtn_Click(object sender, EventArgs e)
		{
            Save();
        }
        
        private void Save()
        {
			if (!ValidateForm(true))
				return;

			if (!_currentTransaction.IsNew)
			{
				if ((bool)DALHelper.GetValue(DepositTransactionFields.IsPriced, DepositTransactionFields.Id, _currentDepositTransaction.Id))
				{
					RetrieveTransaction(false);
					return;
				}
			}

			var transItems = new EntityCollection<TransactionItemEntity>();
			var transItemsToDelete = new EntityCollection<TransactionItemEntity>();

			if (_currentDepositTransaction.IsNew)
			{
				_currentDepositTransaction.SupplierId = _currentSupplyOrder.SupplierId;
				_currentDepositTransaction.SupplyOrderNumber = _currentSupplyOrder.SupplyOrderNumber;

				var transaction = new TransactionEntity()
				{
					ProjectId = _currentSupplyOrder.ProjectId,
					StoreId = GetSelectedStoreId(),
					PermitNumber = PermitNumberTB.Text,
					CreatedBy = UserInfo.UserId,
					Date = AdditionDateDTP.Value.Date,
					Type = "Deposit"
				};

				_currentDepositTransaction.Transaction = transaction;
			}
			else
			{
				DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
			}

			foreach (SupplyOrderItemEntity item in _supplyOrderItems)
			{
				//if (item.QuantityToBeAdded > 0 && item.NewShelfId > 0)
                if (item.QuantityToBeAdded > 0)
				{
					List<TransactionItemEntity> transactionItems = (from t in transItems
                             where t.RequestItemId == item.Id
                             select t).ToList();

                    if (item.ShelvesBalances == null)
                    {
                        item.ShelvesBalances = LoadShelfBalances(transactionItems);
                    }

                    int index = 0;
                    //Loop for all shelves contain items 
                    foreach (ShelfBalance shelfBalance in item.ShelvesBalances)
                    {
                        
                        TransactionItemEntity transItem = new TransactionItemEntity();

                        if (transactionItems == null)
                        {

                            //item.DeliveredQuantity += item.QuantityToBeAdded;
                            item.DeliveredQuantity += (decimal)shelfBalance.Quantity;

                        }
                        else if (transactionItems.Count > 0)
                        {
                            if (transactionItems[index] != null)
                                transItem = transactionItems[index];
                            else
                                transItem = new TransactionItemEntity();

                            //item.DeliveredQuantity += (item.QuantityToBeAdded - transItem.Quantity);
                            item.DeliveredQuantity += ((decimal)shelfBalance.Quantity - transItem.Quantity);

                        }

                        item.LastDeliveryDate = AdditionDateDTP.Value.Date;

                       // transItem.ShelfId = item.NewShelfId;
                        transItem.ShelfId = shelfBalance.ShelfId;
                        transItem.StoreId = _currentDepositTransaction.Transaction.StoreId.Value;
                        transItem.ItemId = item.ItemId;
                        //transItem.Quantity = item.QuantityToBeAdded;
                        transItem.Quantity = (decimal)shelfBalance.Quantity;
                        transItem.RequestItemId = item.Id;
                        transItem.UnitPrice = item.UnitCost * _currentSupplyOrder.CurrencyRate;//item.SupplyOrder.CurrencyRate;//Business.GetItemCost(transItem.StoreId, transItem.ShelfId.Value, transItem.ItemId);

                        _currentDepositTransaction.Transaction.TransactionItems.Add(transItem);
                        index++;
                    }
				}
				else
				{
					var q = (from t in transItems
							 where t.RequestItemId == item.Id
							 select t).FirstOrDefault();

					if (q != null)
					{
						transItemsToDelete.Add(q);
					}
				}
			}

			DALHelper.DeleteCollection(transItemsToDelete);
			if (DALHelper.SaveEntity(_currentDepositTransaction, true))
			{
				_currentSupplyOrder.IsProcessed = true;
				DALHelper.SaveEntity(_currentSupplyOrder);
				DALHelper.SaveCollection(_supplyOrderItems);

				RetrieveTransaction(false);
				MessageBox.Show("تم الحفظ بنجاح.");
			}
		}

        private List<ShelfBalance> LoadShelfBalances(List<TransactionItemEntity> transactionItems)
        {
            List<ShelfBalance> shelfbalances = new List<ShelfBalance>();
            foreach (TransactionItemEntity tie in transactionItems)
            {
                shelfbalances.Add(new ShelfBalance() { ShelfId = tie.ShelfId.Value, Quantity = (double)tie.Quantity });
            }
            return shelfbalances;
        }
        
        private void RetrieveBtn_Click(object sender, EventArgs e)
		{
			RetrieveTransaction(false);
		}		
		private void RetrieveSupplyOrderBtn_Click(object sender, EventArgs e)
		{
			RetrieveSupplyOrder();
		}


		private void PermitNumberTB_Leave(object sender, EventArgs e)
		{
			ValidatePermitNumber();
		}
		private void _tranItemsForm_RowValidating(int rowIndex, ref bool hasErrors)
		{
			var remainderQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[RemainderQuantity.Index];
			var remainderQuantity = (remainderQuantityCell == null) ? 0 : remainderQuantityCell.Value;

			var quantityCell = _transItemsGrid.Rows[rowIndex].Cells[QuantityToBeAdded.Index];
			var quantity = quantityCell.Value;

			if (quantity == null)
				return;

			if ((decimal)quantity > (decimal)remainderQuantity)
			{
				quantityCell.ErrorText = "الكمية المضافة يجب أن لا تتعدى الكمية المتبقية من الطلب.";
				hasErrors = true;
				return;
			}

			quantityCell.ErrorText = string.Empty;
		}


		private void InitializeDataSources()
		{
			_currentTransaction = new TransactionEntity();
			_currentDepositTransaction = new DepositTransactionEntity();
			_currentDepositTransaction.Transaction = _currentTransaction;			

			BindDataSources();

			EnableDisableControls();
		}
		private void BindDataSources()
		{
			_TransBS.DataSource = _currentTransaction;
			_DepositBS.DataSource = _currentDepositTransaction;
		}
		private void LoadData()
		{
			
			DALHelper.FetchCollection(_depositTypes, null, null, new SortExpression(DepositTypeFields.Order | SortOperator.Ascending));
			DALHelper.FetchCollection(_inspectionStatus, null, null, new SortExpression(InspectionTypeFields.Order | SortOperator.Ascending));

			FormsHelper.LoadComboBox(SupplierDDL, SupplierFields.Id, SupplierFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));
			//FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetRunningProjects());
			//FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, ()=>Business.GetStoresForKeeper());

			//FormsHelper.CheckStoresAndProjects(StoresDDL.Items, ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn }, NoStoresLbl, NoProjectsLbl);

			StatusDDL.SelectedIndex = 0;
			TypeDDL.SelectedIndex = 0;
			SupplierDDL.SelectedIndex = 0;
		}
        private bool ValidateForm(bool ValidateGrid)
		{
			var isValid = true;

			var controls = new List<TextBox>();
			controls.Add(PermitNumberTB);
			controls.Add(PRNumberTB);
			controls.Add(PONumberTB);
			controls.Add(SupplyOrderNumberTB);
			controls.Add(ExamRecordNumberTB);
			//controls.Add(BillOfLadingNmberTB);
			//controls.Add(PlateNumberTB);
			//controls.Add(DriverNameTB);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else 
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var tb in controls)
			{
				if (string.IsNullOrEmpty(tb.Text.Trim()))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(tb, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}			
			}

			var combos = new List<ComboBox>();
			//combos.Add(StoresDDL);
			combos.Add(TypeDDL);
			combos.Add(StatusDDL);

			foreach (var cmd in combos)
			{
				if (cmd.SelectedIndex < 0)
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(cmd, "يجب إختيار قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
				}
			}

            if (GetSelectedStoreId() == 0)
            {
                var errorProvider = new ErrorProvider(this);
                _errorProviders.Add(errorProvider);

                errorProvider.SetError(StoresTB, "يجب إدخال قيمة صحيحة ");
                errorProvider.RightToLeft = true;

                isValid = false;

            }

            if (ValidateGrid)
            {
                if (!ValidatePermitNumber())
                    isValid = false;
            }


			_tranItemsForm.ValidateCollection();

			if (_supplyOrderItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}
		private bool ValidatePermitNumber()
		{
			return FormsHelper.ValidatePermitNumber(this, PermitNumberTB, _errorProviders, "Deposit", _currentTransaction.Id);
		}				
		private void GetShelves()
		{
			var storeId = GetSelectedStoreId();
			_shelves.Clear();
			DALHelper.FetchCollection(_shelves, new RelationPredicateBucket(ShelfFields.StoreId == storeId));
		}		
		private void ResetTransactionItems()
		{
			//if (_tranItemsForm != null)
			//{
			//    _tranItemsForm.Dispose();
			//    _tranItemsForm = null;
			//}

			//var label = new Label();
			//_tranItemsForm = new DataMngrFormBase<TransactionItemEntity>(_supplyOrderItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(TransactionItemFields.TransactionId == 0));
			//_tranItemsForm.SetNumericFields(new List<int> { 3 });
			//_tranItemsForm.SetMandatoryFields(new List<int>() { 0, 1, 3 });
		}
		private int GetSelectedStoreId()
		{
            DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
            if (DTStore.Rows.Count > 0)
            {
                return Int32.Parse(DTStore.Rows[0][0].ToString());
            }

            return 0;
		}		
		private void RetrieveTransaction(bool IsNew)
		{
			if (string.IsNullOrEmpty(PermitNumberTB.Text.Trim()))
				return;

			var collection = new EntityCollection<TransactionEntity>();
			var prefetch = new PrefetchPath2(EntityType.TransactionEntity);
			prefetch.Add(TransactionEntity.PrefetchPathDepositTransactions);

			var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");

            if (IsNew)
            {
                //Added by Thabet 
                //retrieve only the all deposit transaction that bind with supply order (if its filled) 
                if (!string.IsNullOrEmpty(SupplyOrderNumberTB.Text))
                {
                    filter.PredicateExpression.Add(new PredicateExpression(DepositTransactionFields.SupplyOrderNumber == SupplyOrderNumberTB.Text));
                }
            }

            filter.PredicateExpression.Add(TransactionFields.PermitNumber == PermitNumberTB.Text.Trim());

            DALHelper.FetchCollection(collection, filter, prefetch);

			if (collection.Count <= 0 || collection[0].DepositTransactions.Count <= 0)
			{
				ResetForm();				
			}
			else
			{
				_currentTransaction = collection[0];
				_currentDepositTransaction = _currentTransaction.DepositTransactions[0];

				RetrieveSupplyOrder(_currentDepositTransaction.SupplyOrderNumber);

                var storefilter = new RelationPredicateBucket(StoreFields.Id == collection[0].StoreId);
                EntityCollection<StoreEntity> Store = new EntityCollection<StoreEntity>();
                DALHelper.FetchCollection(Store, storefilter);
                StoresTB.Text = Store[0].Code;

				BindDataSources();

				var transItems = new EntityCollection<TransactionItemEntity>();
				DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
				foreach (SupplyOrderItemEntity orderItem in _supplyOrderItems)
				{
                    //var q = (from t in transItems
                    //         where t.ItemId == orderItem.ItemId && t.RequestItemId == orderItem.Id
                    //         select t).FirstOrDefault();

                    //if (q == null)
                    //    continue;

                    //orderItem.NewShelfId = q.ShelfId.Value;
                    //orderItem.QuantityToBeAdded = q.Quantity;

                    List<TransactionItemEntity> transactionItems = (from t in transItems
                                                                    where t.ItemId == orderItem.ItemId && t.RequestItemId == orderItem.Id
                                                                    select t).ToList();


                    if (transactionItems == null)
                        continue;

                    //orderItem.NewShelfId = q.ShelfId.Value;
                    orderItem.QuantityToBeAdded = transactionItems.Sum(t => t.Quantity);



                    if (orderItem.ShelvesBalances == null)
                    {
                        orderItem.ShelvesBalances = LoadShelfBalances(transactionItems);
                    }

				}
			}

            //Fill ItemName & ItemCode columns in retrieving transaction 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count - 1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow + 1;

                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }

			ValidatePermitNumber();

			EnableDisableControls();
		}
		private void EnableDisableControls()
		{
            if (_currentDepositTransaction.TransactionStatus == 1)
            {
                _alreadyPricedLbl.Text = "* إذن الإضافه تم حفظه نهائيا ويمكن تسعيره فقط  !";
            }
            else if (_currentDepositTransaction.TransactionStatus == 2)
            {
                _alreadyPricedLbl.Text = "* إذن الإضافه تم تسعيره و لا يمكن تغيير بياناته !";
            }
            else
            {
                _alreadyPricedLbl.Text = String.Empty;
            }

			var valid = (!_currentDepositTransaction.IsPriced) && (_currentSupplyOrder != null) && (!_currentSupplyOrder.IsNew);

            var isSubmitted = _currentDepositTransaction.TransactionStatus > 0;

            var isEditable = !((!valid) || isSubmitted);

            _transItemsGrid.Enabled = isEditable;// valid;
            SaveBtn.Enabled = isEditable;// valid;
            btnSubmit.Enabled = isEditable;
            bindingNavigator1.Enabled = isEditable;// valid;
            _alreadyPricedLbl.Visible = !isEditable; //_currentDepositTransaction.IsPriced;

			//StoresDDL.Enabled = _currentTransaction.IsNew;
			ProjectsTB.Enabled = _currentTransaction.IsNew;
			NewBtn.Enabled = !_currentTransaction.IsNew;
			DeleteBtn.Enabled = !_currentTransaction.IsNew && isEditable;// _currentDepositTransaction.IsPriced);
		}
		private void RetrieveSupplyOrder()
		{
			var supplyOrderNumer = SupplyOrderNumberTB.Text;
			ResetForm();
			RetrieveSupplyOrder(supplyOrderNumer);
			EnableDisableControls();

            //Fill ItemName & ItemCode columns in retrieving transaction 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count - 1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow + 1;

                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }
		}
		private void RetrieveSupplyOrder(string supplyOrderNumber)
		{
			if (string.IsNullOrEmpty(supplyOrderNumber.Trim()))
				return;

			var collection = new EntityCollection<SupplyOrderEntity>();

			var filter = new RelationPredicateBucket(SupplyOrderFields.SupplyOrderNumber == supplyOrderNumber.Trim());
			filter.PredicateExpression.Add(ProjectFields.IsGeneral == false);
			filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

			DALHelper.FetchCollection(collection, filter);

			if (collection.Count <= 0)
			{
				_currentSupplyOrder = new SupplyOrderEntity();
				_SupplyOrderBS.DataSource = _currentSupplyOrder;
			}
			else
			{
                var projectfilter = new RelationPredicateBucket(ProjectFields.Id == collection[0].ProjectId);
                EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
                DALHelper.FetchCollection(project, projectfilter);
                ProjectsTB.Text = project[0].Code;
				_currentSupplyOrder = collection[0];
				_SupplyOrderBS.DataSource = _currentSupplyOrder;
			}
			//_requestItems.Clear();
			//DALHelper.FetchCollection(_requestItems, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == _currentRequest.Id));			
			LoadSupplyOrderItems(_currentSupplyOrder.Id);
			//EnableDisableControls();
		}
		private void LoadSupplyOrderItems(int supplyOrderId)
		{
			if (_tranItemsForm != null)
			{
				_tranItemsForm.Dispose();
				_tranItemsForm = null;
			}

			var prefetch = new PrefetchPath2(EntityType.SupplyOrderItemEntity);
			prefetch.Add(SupplyOrderItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);

			var label = new Label();
			_tranItemsForm = new DataMngrFormBase<SupplyOrderItemEntity>(_supplyOrderItems, _transItemsGrid, _SupplyOrderItemsBS, new Button(), label, label, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == supplyOrderId), prefetch);
			_tranItemsForm.SetNumericFields(new List<int> { QuantityToBeAdded.Index });
            _tranItemsForm.SetMandatoryFields(new List<int>() { NewShelfId.Index, QuantityToBeAdded.Index });
			_tranItemsForm.RowValidating += new DataMngrFormBase<SupplyOrderItemEntity>.RaiseRowValidating(_tranItemsForm_RowValidating);
		}
		private void ResetForm()
		{
			_currentSupplyOrder = new SupplyOrderEntity();
			_currentDepositTransaction = new DepositTransactionEntity();
			_currentDepositTransaction.Transaction = new TransactionEntity();
			_supplyOrderItems.Clear();

            ProjectsTB.Text = "";
            StoresTB.Text = "";

			_DepositBS.DataSource = _currentDepositTransaction;
			_TransBS.DataSource = _currentDepositTransaction.Transaction;
			_SupplyOrderBS.DataSource = _currentSupplyOrder;

			EnableDisableControls();
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
            //Open the search form for products using code or name 
            if (e.ColumnIndex == ItemCodeColumn.Index)
            {
                var itemPickerForm = new ItemPickerForm(1);
                if (itemPickerForm.ShowDialog() == DialogResult.OK)
                {
                    GetItemDetailsByItemId(e.RowIndex, itemPickerForm.SelectedItemId);

                }
            }
            else if (e.ColumnIndex == QuantityToBeAdded.Index)
            {
                if (!ValidateForm(false))
                {

                    return;
                }
                double availableBalance = Double.Parse(_transItemsGrid.Rows[e.RowIndex].Cells[RemainderQuantity.Index].Value.ToString());
                int itemId = Int32.Parse(_transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value.ToString());

                

                if (_transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value.ToString() == "0")
                {

                    ShelfBalanceForm shelfBalanceFrm = new ShelfBalanceForm(GetSelectedStoreId(), itemId, availableBalance, _currentTransaction.Id);
                    shelfBalanceFrm.ShowDialog();


                    _transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value = shelfBalanceFrm.allItemsShelvesBalancesValue.ToString();

                    ((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances = shelfBalanceFrm.ItemShelvesBalances;
                }
                else
                {
                    ShelfBalanceForm shelfBalanceFrm = new ShelfBalanceForm(((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances, availableBalance, GetSelectedStoreId());
                    shelfBalanceFrm.ShowDialog();

                    _transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value = shelfBalanceFrm.allItemsShelvesBalancesValue.ToString();

                    ((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances = shelfBalanceFrm.ItemShelvesBalances;
                }

                _transItemsGrid.Refresh();
                //var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value;
                //if (itemIdValue == null)
                //    return;

                //var form = new UnitConverterForm((int)itemIdValue);
                //if (form.ShowDialog() == DialogResult.OK)
                //{
                //    _transItemsGrid.SuspendLayout();
                //    _transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
                //    _transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
                //    _transItemsGrid.ResumeLayout(true);
                //}
            }
		}

		private void SearchBtn_Click(object sender, EventArgs e)
		{
			var supplyOrderRelations = new RelationCollection();
			supplyOrderRelations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

			var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");

            //Added by Thabet 
            //retrieve only the all deposit transaction that bind with supply order (if its filled) 
            if (!string.IsNullOrEmpty(SupplyOrderNumberTB.Text))
            {
                filter.PredicateExpression.Add(new PredicateExpression(DepositTransactionFields.SupplyOrderNumber == SupplyOrderNumberTB.Text));
            }

			filter.Relations.Add(TransactionEntity.Relations.ProjectEntityUsingProjectId);
			filter.Relations.Add(TransactionEntity.Relations.DepositTransactionEntityUsingTransactionId);
			filter.PredicateExpression.Add(
				new FieldCompareSetPredicate(DepositTransactionFields.SupplyOrderNumber, null, SupplyOrderFields.SupplyOrderNumber, null, SetOperator.In,
					new PredicateExpression(ProjectFields.IsGeneral == false), supplyOrderRelations));

			var searchForm = new SearchForm(TransactionFields.PermitNumber, TransactionFields.ProjectId, TransactionFields.Date, filter, () => Business.GetRunningProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				PermitNumberTB.Text = searchForm.SelectedNumber;
				RetrieveTransaction(true);
			}
		}

		private void SearchSupplyOrderBtn_Click(object sender, EventArgs e)
		{
			var filter = new RelationPredicateBucket();
			filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);
			filter.PredicateExpression.Add(ProjectFields.IsGeneral == false);

			var searchForm = new SearchSupplyOrderForm(SupplyOrderFields.SupplyOrderNumber, SupplyOrderFields.ProjectId, SupplyOrderFields.Date, filter, () => Business.GetRunningProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				SupplyOrderNumberTB.Text = searchForm.SelectedNumber;
				RetrieveSupplyOrder();
			}
		}

		private void DeleteBtn_Click(object sender, EventArgs e)
		{
			var form = new DeleteConfirmationForm();

			if (form.ShowDialog() == DialogResult.Yes)
			{
				if (DALHelper.DeleteEntity(_currentTransaction))
				{
					ResetForm();
				}
			}
		}

        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemId
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex"> Index of row in data grid</param>
        /// <param name="itemId">The ID of item(Product)</param>
        private void GetItemDetailsByItemId(int rowIndex, int itemId)
        {
            DataTable itemDT = Business.GetItemDetails(itemId);
            if (itemDT.Rows.Count <= 0)
                return;

            _transItemsGrid.Rows[rowIndex].Cells[ItemCodeColumn.Index].Value = itemDT.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = itemDT.Rows[0][1].ToString();

            _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = itemId;

            return;
        }
        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemCode
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex">Index of row in data grid</param>
        /// <param name="itemCode">The code of item</param>
        private void GetItemDetailsByItemCode(int rowIndex, string itemCode)
        {
            var dt = Business.GetItemDetails(itemCode, 1);
            if (dt.Rows.Count <= 0)
                return;

            _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = dt.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = dt.Rows[0][1].ToString();

            return;
        }

        private void _transItemsGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if ((e.ColumnIndex == ItemCodeColumn.Index) && (_transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value != null))
            {
                string productItemCode = _transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value.ToString();
                GetItemDetailsByItemCode(e.RowIndex, productItemCode);
            }
        }

        private void _transItemsGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            _transItemsGrid.Rows[e.RowIndex].Cells[SequenceColumn.Index].Value = e.RowIndex + 1;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            var form = new SaveConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                _currentDepositTransaction.TransactionStatus = 1;
                Save();
                Business.StoreItems(GetSelectedStoreId(), _currentDepositTransaction, _currentTransaction);
            }

        }

        private void ProjectsTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ProjectsTB.Text))
            {
                ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text);

                if (project != null)
                {
                    lblProjectName.Text = project.Name;
                    EnableDisableControls();
                    Business.GetSupplyOrderItemsPlannedForProject(project.Id, _items);

                    var filter = new RelationPredicateBucket();
                    filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));

                    ResetTransactionItems();

                    EnableDisableControls();
                }
                else
                {
                    lblProjectName.Text = string.Empty;
                }


            }
            else
            {
                lblProjectName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }

        private void SearchProjectBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();
            var filter = new RelationPredicateBucket();
            var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                            () => Business.GetRunningAndGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                ProjectsTB.Text = searchForm.SelectedNumber;

                EnableDisableControls();
            }
        }

        private void StoresTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(StoresTB.Text))
            {
                DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
                if (DTStore.Rows.Count > 0)
                {
                    lblStoreName.Text = DTStore.Rows[0][2].ToString();
                    EnableDisableControls();
                }
                else
                {
                    lblStoreName.Text = string.Empty;
                    //RunBtn.Enabled = false;
                }
            }
            else
            {
                lblStoreName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }

        private void SearchStoresBtn_Click(object sender, EventArgs e)
        {
            var searchForm = new fromGeneralEntityPicker("Store");
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                StoresTB.Text = searchForm.SelectedItemCode;

            }
        }

	}
}
